<template>
  <div class="admin-comments">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>评论管理</h2>
        </div>
      </template>
      
      <div class="table-toolbar">
        <el-form :inline="true" class="search-form">
          <el-form-item>
            <el-input
              v-model="searchQuery"
              placeholder="搜索评论内容"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="statusFilter" placeholder="状态" clearable>
              <el-option label="正常" value="0" />
              <el-option label="已删除" value="1" />
              <el-option label="被举报" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="content" label="评论内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="articleTitle" label="文章标题" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            <el-link type="primary" @click="viewArticle(scope.row)">{{ scope.row.articleTitle }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="评论者" width="120" />
        <el-table-column prop="createTime" label="评论时间" width="180" sortable />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === 0 ? 'success' : (scope.row.status === 2 ? 'warning' : 'danger')"
            >
              {{ 
                scope.row.status === 0 ? '正常' : 
                (scope.row.status === 2 ? '被举报' : '已删除') 
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleViewReports(scope.row)" v-if="scope.row.status === 2">
              查看举报
            </el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              @click="handleToggleStatus(scope.row)"
              :disabled="scope.row.status === 1"
            >
              {{ scope.row.status === 1 ? '已删除' : '删除' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 举报详情对话框 -->
    <el-dialog
      v-model="reportDialogVisible"
      title="举报详情"
      width="600px"
    >
      <div v-if="currentComment" class="report-dialog-content">
        <div class="comment-info">
          <h3>评论内容</h3>
          <p>{{ currentComment.content }}</p>
          <div class="meta-info">
            <span>评论者: {{ currentComment.user }}</span>
            <span>评论时间: {{ currentComment.createTime }}</span>
          </div>
          <el-divider></el-divider>
        </div>
        
        <h3>举报列表</h3>
        <el-table :data="reportList" border>
          <el-table-column prop="reporter" label="举报者" width="120" />
          <el-table-column prop="reason" label="举报原因" />
          <el-table-column prop="createTime" label="举报时间" width="180" />
        </el-table>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reportDialogVisible = false">关闭</el-button>
          <el-button type="danger" @click="handleDeleteReportedComment">删除评论</el-button>
          <el-button type="primary" @click="handleIgnoreReports">忽略举报</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import api from '@/api'

export default {
  name: 'AdminComments',
  
  setup() {
    const router = useRouter()
    
    // 表格数据和加载状态
    const tableData = ref([])
    const loading = ref(true)
    
    // 分页参数
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 搜索过滤条件
    const searchQuery = ref('')
    const statusFilter = ref('')
    
    // 举报对话框
    const reportDialogVisible = ref(false)
    const currentComment = ref(null)
    const reportList = ref([])
    
    // 获取评论列表
    const fetchComments = async () => {
      loading.value = true
      try {
        // 构建请求参数
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          keyword: searchQuery.value,
          status: statusFilter.value
        }
        
        console.log('开始请求评论列表, 参数:', params)
        
        // 调用API获取评论列表
        const response = await api.admin.getCommentList(params)
        console.log('获取评论列表响应:', response)

        // 添加响应检查
        if (response && response.code === 0) {
          console.log('响应数据:', response.data)
          
          // 适应不同的后端返回格式
          let list = []
          let totalCount = 0
          
          if (response.data && typeof response.data === 'object') {
            if (Array.isArray(response.data)) {
              // 如果直接返回数组
              list = response.data
              totalCount = response.data.length
            } else {
              // 如果返回对象，包含list和total
              list = response.data.list || []
              totalCount = response.data.total || 0
            }
          }
          
          console.log('处理后的数据:', { list, totalCount })
          
          tableData.value = list
          total.value = totalCount
        } else {
          tableData.value = []
          total.value = 0
          const errorMsg = response ? response.message || '获取评论列表失败' : '获取评论列表失败'
          console.warn('评论列表请求失败:', errorMsg)
          ElMessage.warning(errorMsg)
        }
      } catch (error) {
        console.error('获取评论列表失败:', error)
        tableData.value = []
        total.value = 0
        ElMessage.error('获取评论列表失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }
    
    // 搜索处理
    const handleSearch = () => {
      currentPage.value = 1
      fetchComments()
    }
    
    // 重置搜索条件
    const resetSearch = () => {
      searchQuery.value = ''
      statusFilter.value = ''
      currentPage.value = 1
      fetchComments()
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      fetchComments()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchComments()
    }
    
    // 查看文章
    const viewArticle = (row) => {
      router.push({ name: 'ArticleDetail', params: { id: row.articleId } })
    }
    
    // 查看举报
    const handleViewReports = async (row) => {
      currentComment.value = row
      
      try {
        loading.value = true
        console.log('获取评论举报，评论ID:', row.id)
        
        // 调用API获取举报列表
        const response = await api.admin.getCommentReports(row.id)
        console.log('获取举报列表响应:', response)
        
        if (response.code === 0) {
          reportList.value = response.data || []
          console.log('举报列表数据:', reportList.value)
        } else {
          reportList.value = []
          const errorMsg = response.message || '获取举报列表失败'
          console.warn('获取举报列表失败:', errorMsg)
          ElMessage.warning('获取举报列表失败: ' + errorMsg)
        }
      } catch (error) {
        console.error('获取举报列表失败:', error)
        reportList.value = []
        ElMessage.error('获取举报列表失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
        reportDialogVisible.value = true
      }
    }
    
    // 切换评论状态（删除/恢复）
    const handleToggleStatus = (row) => {
      const action = row.status === 1 ? '恢复' : '删除'
      ElMessageBox.confirm(`确定要${action}该评论吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          if (row.status !== 1) {
            await api.admin.deleteComment(row.id)
            row.status = 1
            ElMessage.success(`${action}成功`)
          }
        } catch (error) {
          console.error(`${action}失败:`, error)
          ElMessage.error(`${action}失败: ` + (error.message || '未知错误'))
        }
      }).catch(() => {})
    }
    
    // 删除被举报的评论
    const handleDeleteReportedComment = async () => {
      if (!currentComment.value) return
      
      ElMessageBox.confirm('确定要删除该评论吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await api.admin.deleteComment(currentComment.value.id)
          currentComment.value.status = 1
          ElMessage.success('删除成功')
          reportDialogVisible.value = false
          fetchComments() // 刷新列表
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.error('删除失败: ' + (error.message || '未知错误'))
        }
      }).catch(() => {})
    }
    
    // 忽略举报
    const handleIgnoreReports = async () => {
      if (!currentComment.value) return
      
      ElMessageBox.confirm('确定要忽略所有举报吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          console.log('忽略评论举报，评论ID:', currentComment.value.id)
          const response = await api.admin.ignoreCommentReports(currentComment.value.id)
          console.log('忽略评论举报响应:', response)
          
          if (response.code === 0) {
            currentComment.value.status = 0
            ElMessage.success('已忽略所有举报')
            reportDialogVisible.value = false
            fetchComments() // 刷新列表
          } else {
            const errorMsg = response.message || '操作失败'
            console.warn('忽略举报失败:', errorMsg)
            ElMessage.error('操作失败: ' + errorMsg)
          }
        } catch (error) {
          console.error('操作失败:', error)
          ElMessage.error('操作失败: ' + (error.message || '未知错误'))
        }
      }).catch(() => {})
    }
    
    // 删除评论
    const handleDeleteComment = (row) => {
      ElMessageBox.confirm('删除评论将无法恢复，是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await api.admin.deleteComment(row.id)
          ElMessage.success('删除成功')
          fetchComments() // 刷新列表
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.error('删除失败: ' + (error.message || '未知错误'))
        }
      }).catch(() => {})
    }
    
    onMounted(() => {
      fetchComments()
    })
    
    return {
      tableData,
      loading,
      currentPage,
      pageSize,
      total,
      searchQuery,
      statusFilter,
      reportDialogVisible,
      currentComment,
      reportList,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      viewArticle,
      handleViewReports,
      handleToggleStatus,
      handleDeleteReportedComment,
      handleIgnoreReports,
      handleDeleteComment
    }
  }
}
</script>

<style scoped>
.admin-comments {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
}

.table-toolbar {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.report-dialog-content {
  max-height: 60vh;
  overflow-y: auto;
}

.comment-info {
  margin-bottom: 20px;
}

.comment-info h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.meta-info {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 14px;
  margin-top: 10px;
}
</style>